package com.lpb.spring.lpbspring.aop.proxy;

import com.lpb.spring.lpbspring.aop.advisor.Advisor;
import com.lpb.spring.lpbspring.aop.proxy.weaving.AopProxyWeaving;
import com.lpb.spring.lpbspring.ioc.BeanFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @ClassName JdkProxy
 * @Description TODO
 * @date 2022/12/9 01:15
 * @Version 1.0
 * @authoe linpengbo
 */
public class JdkProxy implements AopProxy, InvocationHandler {


    //被代理的目标对象
    private Object target;
    //被代理对象的所有切面集合
    private List<Advisor> advisorList;
    //对beanFactory的引用
    private BeanFactory beanFactory;

    public JdkProxy(Object target, List<Advisor> advisorList, BeanFactory beanFactory) {
        super();
        this.target = target;
        this.advisorList = advisorList;
        this.beanFactory = beanFactory;
    }

    @Override
    public Object getProxy() throws Exception {
        return this.getProxy(target.getClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader cld) throws Exception {

        return Proxy.newProxyInstance(cld, target.getClass().getInterfaces(), this);
    }

    /**
     * 执行代理对象的方法 真正被执行的方法，这里面要完成切面增强功能向 原方法功能的织入
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return AopProxyWeaving.applyAdvisor(this.target, method, args, this.advisorList, this.beanFactory);
    }
}
